//
//  VCPhotoViewController.m
//  VideoCollage
//
//  Created by Mac on 2018/6/25.
//  Copyright © 2018年 stoneobs.qq.com. All rights reserved.
//

#import "VCPhotoViewController.h"
#import "TZAssetCell.h"
#import "STPhotoSystemBrowserController.h"
#import "VCPhotoLookViewController.h"
@interface VCPhotoViewController ()
<UICollectionViewDataSource,UICollectionViewDelegate,UIImagePickerControllerDelegate,UICollectionViewDelegateFlowLayout,STPhotoSystemBrowserControllerDlegate>

@property(nonatomic, strong) NSIndexPath                     *currentIndexPath;/**< <##> */
@end

@implementation VCPhotoViewController
- (void)setAssetsArray:(NSArray *)assetsArray{
    _assetsArray = assetsArray;
    [self.collectionView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.collectionView];
    [self addNotifacations];
    // Do any additional setup after loading the view.
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onReciveModelSelctedNotify:)
                                                 name:modelSelctedNotifation
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onReciveModelUnSelctedNotify:)
                                                 name:modelUnSelctedNotifation
                                               object:nil];
    
}
- (void)onReciveModelSelctedNotify:(NSNotification*)notify{
    if ([notify.userInfo[@"sendVC"] isEqualToString:NSStringFromClass(self.class)]) {
        //自己发送的通知不刷新
        return;
    }
   // [self.collectionView reloadData];
}
- (void)onReciveModelUnSelctedNotify:(NSNotification*)notify{
    if ([notify.userInfo[@"sendVC"] isEqualToString:NSStringFromClass(self.class)]) {
        //自己发送的通知不刷新
        return;
    }
   // [self.collectionView reloadData];
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
        flow.minimumLineSpacing = 5;
        flow.minimumInteritemSpacing = 5;
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.sectionInset = UIEdgeInsetsMake(0,10 ,0, 10);
        
        VCAssetChosedViewController * vc = (id)self.parentViewController;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, vc.scrollView.height) collectionViewLayout:flow];
        _collectionView.backgroundColor = TM_backgroundColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        //注册
        [_collectionView registerClass:[TZAssetCell class] forCellWithReuseIdentifier:@"item"];
        self.automaticallyAdjustsScrollViewInsets = NO;
        if (ios11) {
            if ([_collectionView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
                [_collectionView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2) afterDelay:0];
            }
        }
    }
    return _collectionView;
}
#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.assetsArray.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat itemWith = (UIScreenWidth - 20 - 15)/4;
    return CGSizeMake(itemWith, itemWith);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TZAssetCell * cell = (TZAssetCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    cell.showSelectBtn = YES;
    cell.allowPreview = YES;
    cell.useCachedImage = YES;
    cell.allowPickingMultipleVideo = YES;
    cell.photoDefImage =  [UIImage imageNamedFromMyBundle:@"photo_def_photoPickerVc"];
    cell.photoSelImage =  [UIImage imageNamedFromMyBundle:@"photo_sel_photoPickerVc"];
    TZAssetModel * model = self.assetsArray[indexPath.row];
    cell.model = model;
    
    __weak typeof(cell) weakCell = cell;
    __weak typeof(self) weakSelf = self;
    VCAssetChosedViewController * faterVc = (id)self.parentViewController;
    cell.didSelectPhotoBlock = ^(BOOL isSelected) {
        __strong typeof(weakCell) strongCell = weakCell;
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        // 1. cancel select / 取消选择
        if (isSelected) {
            strongCell.selectPhotoButton.selected = NO;
            model.isSelected = NO;
            
            NSArray *selectedModels = [NSArray arrayWithArray:faterVc.selectedModels];
            for (TZAssetModel *model_item in selectedModels) {
                if ([[[TZImageManager manager] getAssetIdentifier:model.asset] isEqualToString:[[TZImageManager manager] getAssetIdentifier:model_item.asset]]) {
                    [faterVc removeSelectedModel:model_item];
                    break;
                }
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:modelUnSelctedNotifation object:model userInfo:@{@"sendVC":NSStringFromClass(self.class)}];
            
            //            if (tzImagePickerVc.showSelectedIndex || tzImagePickerVc.showPhotoCannotSelectLayer) {
            //                [strongSelf setUseCachedImageAndReloadData];
            //            }
            //            [UIView showOscillatoryAnimationWithLayer:strongLayer type:TZOscillatoryAnimationToSmaller];
        } else {
            // 2. select:check if over the maxImagesCount / 选择照片,检查是否超过了最大个数的限制
            if (faterVc.selectedModels.count >= faterVc.itemView.itemImageViewArray.count) {
                [SVProgressHUD showInfoWithStatus:@"More than the maximum number of selected sheets"];
                return ;
            }
            strongCell.selectPhotoButton.selected = YES;
            model.isSelected = YES;
            [faterVc addSelectedModel:model];
            [[NSNotificationCenter defaultCenter] postNotificationName:modelSelctedNotifation object:model userInfo:@{@"sendVC":NSStringFromClass(self.class)}];
        }
    };
    
    return cell;
}
#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
     TZAssetModel * model = self.assetsArray[indexPath.row];
    if (model.type == TZAssetModelMediaTypePhoto) {
        VCPhotoLookViewController * vc = [VCPhotoLookViewController new];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (model.type == TZAssetModelMediaTypeVideo) {
        TZVideoPlayerController * vc = TZVideoPlayerController.new;
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
#pragma mark --STPhotoSystemBrowserControllerDlegate
- (UIView *)STPhotoSystemBrowserControllerDidScrollToIndexpath:(NSIndexPath*)indexPath model:(STPhotoModel*)model{
    TZAssetCell * cell  = (id)[self.collectionView cellForItemAtIndexPath:indexPath];
    return cell.imageView;
}
@end
